import React, { useEffect, useState } from 'react'
import { applyEmotionColors, getEmotionColors } from '../utils/emotionColors'

const DynamicBackground = ({
  generatedImage,
  emotion,
  isVisible = false,
  hideMainContent = false,
  history = [],
  currentRecordId = null,
  onRecordChange = null,
  onClosePreview = null
}) => {
  const [imageLoaded, setImageLoaded] = useState(false)
  const [showImage, setShowImage] = useState(false)

  // 获取当前应该显示的图片 - 始终从历史记录中根据 currentRecordId 获取
  const getCurrentImage = () => {
    if (currentRecordId && history.length > 0) {
      const currentRecord = history.find(record => record.id === currentRecordId)
      const targetImage = currentRecord?.generatedImage || null
      console.log('📱 DynamicBackground - 获取当前图片 - 记录ID:', currentRecordId, '找到图片:', !!targetImage?.imageUrl)
      return targetImage
    }
    console.log('❌ DynamicBackground - 未找到有效记录，或无 currentRecordId')
    return null
  }

  const currentImage = getCurrentImage()

  // 应用情绪色彩
  useEffect(() => {
    if (emotion) {
      applyEmotionColors(emotion)
    }
  }, [emotion])

  // 统一的图片显示控制逻辑 - 确保有图片URL就显示
  useEffect(() => {
    console.log('🔍 DynamicBackground - 图片显示逻辑检查:', {
      currentRecordId: currentRecordId,
      hasImage: !!currentImage?.imageUrl,
      imageSuccess: currentImage?.success,
      hideMainContent: hideMainContent,
      imageUrl: currentImage?.imageUrl ? currentImage.imageUrl.substring(0, 100) + '...' : 'N/A'
    })

    if (currentImage?.imageUrl) {
      console.log('✅ DynamicBackground - 检测到图片URL，准备显示:', currentImage.imageUrl.substring(0, 100) + '...')
      setImageLoaded(false) // 重置加载状态，以便新图片重新加载
      setShowImage(true)
    } else {
      console.log('❌ DynamicBackground - 没有有效图片URL，隐藏显示')
      setShowImage(false)
      setImageLoaded(false)
    }
  }, [currentImage?.imageUrl, currentRecordId, generatedImage?.imageUrl]) // 添加 generatedImage.imageUrl 依赖

  const handleImageLoad = () => {
    console.log('✅ DynamicBackground - 图片加载成功:', currentImage?.imageUrl)
    setImageLoaded(true)
  }

  const handleImageError = (e) => {
    console.warn('❌ DynamicBackground - 背景图片加载失败:', currentImage?.imageUrl?.substring(0, 100) + '...')

    // 尝试使用 originalSample 作为备用方案（如果存在且不同于当前URL）
    if (currentImage?.originalSample && currentImage.imageUrl !== currentImage.originalSample) {
      console.log('🔄 DynamicBackground - 尝试使用原始URL作为备用方案:', currentImage.originalSample.substring(0, 100) + '...')
      e.target.src = currentImage.originalSample
      return // 不立即标记为失败，给原始URL一个机会
    }

    // 如果所有URL都失败，生成一个本地备用背景
    console.warn('⚠️ DynamicBackground - 所有图片URL都失败，生成本地备用背景')
    setImageLoaded(false)

    // 生成一个简单的渐变背景作为备用
    generateFallbackBackground(e.target)
  }

  // 生成备用背景
  const generateFallbackBackground = (imgElement) => {
    // 创建一个canvas作为备用背景
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    canvas.width = 1024
    canvas.height = 576

    // 根据情绪创建渐变背景
    const emotionColors = emotion ? getEmotionColors(emotion) : null
    const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height)

    if (emotionColors) {
      gradient.addColorStop(0, emotionColors.primary + '40')
      gradient.addColorStop(0.5, emotionColors.secondary + '30')
      gradient.addColorStop(1, emotionColors.accent + '20')
    } else {
      gradient.addColorStop(0, '#f7fafc')
      gradient.addColorStop(0.5, '#edf2f7')
      gradient.addColorStop(1, '#e2e8f0')
    }

    ctx.fillStyle = gradient
    ctx.fillRect(0, 0, canvas.width, canvas.height)

    // 添加一些装饰元素
    ctx.fillStyle = 'rgba(255, 255, 255, 0.1)'
    for (let i = 0; i < 15; i++) {
      const x = Math.random() * canvas.width
      const y = Math.random() * canvas.height
      const radius = Math.random() * 30 + 10
      ctx.beginPath()
      ctx.arc(x, y, radius, 0, Math.PI * 2)
      ctx.fill()
    }

    // 将canvas转换为图片URL并设置
    imgElement.src = canvas.toDataURL('image/jpeg', 0.8)
    setImageLoaded(true) // 标记为已加载
  }

  const emotionColors = emotion ? getEmotionColors(emotion) : null

  return (
    <div className={`fixed inset-0 overflow-hidden ${hideMainContent ? 'pointer-events-auto' : 'pointer-events-none'}`}>
      {/* 情绪色彩背景 */}
      <div 
        className={`absolute inset-0 transition-all duration-3000 ease-in-out ${
          emotion ? 'emotion-background' : 'bg-gradient-to-br from-paper-200 via-paper-100 to-paper-50'
        }`}
        style={{
          background: emotionColors?.background || 'linear-gradient(135deg, #f8f4e8 0%, #f2ecd8 100%)'
        }}
      />

      {/* 生成的图片作为主背景 - 简化条件，确保有图片就显示 */}
      {showImage && currentImage?.imageUrl && (
        <div className={`absolute inset-0 transition-all duration-500 ease-in-out ${
          imageLoaded ? 'opacity-100' : 'opacity-20'
        }`}>
          {/* 主背景图片 - 清晰显示 */}
          <img
            src={currentImage.imageUrl}
            alt="AI生成的诗意背景"
            className="w-full h-full object-cover"
            onLoad={handleImageLoad}
            onError={handleImageError}
            style={{
              filter: 'brightness(0.85) contrast(1.1) saturate(1.2)', // 保持清晰，稍微调暗
              opacity: 0.9 // 高透明度，让图片清晰可见
            }}
          />

          {/* 图片加载失败时的占位符 */}
          {!imageLoaded && (
            <div className="absolute inset-0 flex items-center justify-center bg-gradient-to-br from-paper-200 via-paper-100 to-paper-50">
              <div className="text-center text-ink-400">
                <div className="text-4xl mb-2 opacity-50">🖼️</div>
                <p className="text-sm">背景图片加载中...</p>
                {currentImage?.originalSample && (
                  <p className="text-xs mt-2 opacity-70">如果加载失败，将尝试备用方案</p>
                )}
              </div>
            </div>
          )}

          {/* 轻微的诗意遮罩 - 增强可读性 */}
          <div
            className="absolute inset-0"
            style={{
              background: `
                linear-gradient(
                  to bottom,
                  rgba(255, 255, 255, 0.1) 0%,
                  transparent 20%,
                  transparent 80%,
                  rgba(0, 0, 0, 0.1) 100%
                ),
                radial-gradient(
                  ellipse at center,
                  transparent 30%,
                  rgba(255, 255, 255, 0.05) 100%
                )
              `
            }}
          />

          {/* 情绪色彩点缀 */}
          <div
            className="absolute inset-0 opacity-20"
            style={{
              background: `
                radial-gradient(circle at 10% 20%, ${emotionColors?.primary}15 0%, transparent 30%),
                radial-gradient(circle at 90% 80%, ${emotionColors?.secondary}12 0%, transparent 25%),
                radial-gradient(circle at 70% 10%, ${emotionColors?.accent}10 0%, transparent 20%)
              `,
              backgroundSize: '400px 400px, 300px 300px, 250px 250px'
            }}
          />
        </div>
      )}

      {/* 轻柔的诗意装饰元素 - 不干扰主背景 */}
      {emotion && !showImage && (
        <div className="absolute inset-0 overflow-hidden">
          {/* 只在没有图片时显示装饰粒子 */}
          {[...Array(8)].map((_, i) => (
            <div
              key={`decoration-${i}`}
              className="absolute rounded-full opacity-10"
              style={{
                left: `${Math.random() * 100}%`,
                top: `${Math.random() * 100}%`,
                width: `${Math.random() * 60 + 30}px`,
                height: `${Math.random() * 60 + 30}px`,
                background: `radial-gradient(circle, ${emotionColors?.primary}30 0%, transparent 70%)`,
                filter: 'blur(20px)',
                animation: `float ${Math.random() * 20 + 25}s ease-in-out infinite`,
                animationDelay: `${Math.random() * 8}s`
              }}
            />
          ))}
        </div>
      )}

      {/* 有图片时的微妙装饰 */}
      {emotion && showImage && (
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
          {/* 边角的轻微光晕 */}
          <div
            className="absolute top-0 left-0 w-32 h-32 opacity-5"
            style={{
              background: `radial-gradient(circle, ${emotionColors?.primary}60 0%, transparent 70%)`,
              filter: 'blur(15px)'
            }}
          />
          <div
            className="absolute bottom-0 right-0 w-40 h-40 opacity-5"
            style={{
              background: `radial-gradient(circle, ${emotionColors?.secondary}50 0%, transparent 70%)`,
              filter: 'blur(20px)'
            }}
          />
        </div>
      )}

      {/* 轻微的诗意纹理 - 只在没有图片时显示 */}
      {emotion && !showImage && (
        <div className="absolute inset-0 opacity-8">
          <div
            className="w-full h-full"
            style={{
              backgroundImage: `
                radial-gradient(ellipse at 20% 50%, ${emotionColors?.accent || '#b45309'}15 0%, transparent 50%),
                radial-gradient(ellipse at 80% 20%, ${emotionColors?.primary || '#d97706'}12 0%, transparent 45%),
                radial-gradient(ellipse at 40% 80%, ${emotionColors?.secondary || '#f59e0b'}10 0%, transparent 40%)
              `,
              backgroundSize: '300px 250px, 250px 200px, 280px 220px',
              backgroundPosition: '0 0, 100px 80px, 200px 40px'
            }}
          />
        </div>
      )}

      {/* 情绪标签显示 - 适应背景图片 */}
      {emotion && !hideMainContent && (
        <div className="absolute top-4 left-4 z-10">
          <div
            className={`px-4 py-2 rounded-full border transition-all duration-1000 ${
              showImage ? 'backdrop-blur-md shadow-lg' : 'backdrop-blur-sm'
            }`}
            style={{
              backgroundColor: showImage
                ? `rgba(255, 255, 255, 0.9)`
                : `${emotionColors?.primary}20`,
              borderColor: showImage
                ? `${emotionColors?.primary}60`
                : `${emotionColors?.primary}40`,
              color: showImage
                ? emotionColors?.primary
                : emotionColors?.text,
              boxShadow: showImage
                ? `0 8px 32px rgba(0, 0, 0, 0.1)`
                : 'none'
            }}
          >
            <span className="text-sm font-medium">
              {emotion} · {emotionColors?.description}
            </span>
          </div>
        </div>
      )}

      {/* 历史记录导航控件 - 只在全屏预览时显示 */}
      {hideMainContent && history.length > 0 && currentRecordId && (
        <HistoryNavigationControls
          history={history}
          currentRecordId={currentRecordId}
          onRecordChange={onRecordChange}
          onClosePreview={onClosePreview}
        />
      )}

    </div>
  )
}

// 历史记录导航控件组件
const HistoryNavigationControls = ({ history, currentRecordId, onRecordChange, onClosePreview }) => {
  const [currentIndex, setCurrentIndex] = useState(0)

  // 找到当前记录在历史中的索引
  useEffect(() => {
    if (currentRecordId && history.length > 0) {
      const index = history.findIndex(record => record.id === currentRecordId)
      if (index !== -1) {
        setCurrentIndex(index)
      }
    }
  }, [currentRecordId, history])

  // 获取当前记录
  const currentRecord = history[currentIndex]

  // 上一个记录
  const handlePrevious = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (currentIndex > 0) {
      const newIndex = currentIndex - 1
      setCurrentIndex(newIndex)
      onRecordChange && onRecordChange(history[newIndex])
    }
  }

  // 下一个记录
  const handleNext = (e) => {
    e.preventDefault()
    e.stopPropagation()
    if (currentIndex < history.length - 1) {
      const newIndex = currentIndex + 1
      setCurrentIndex(newIndex)
      onRecordChange && onRecordChange(history[newIndex])
    }
  }

  // 键盘导航和触摸手势
  useEffect(() => {
    let touchStartX = 0
    let touchStartY = 0
    let touchEndX = 0
    let touchEndY = 0

    const handleKeyDown = (e) => {
      if (e.key === 'ArrowLeft') {
        e.preventDefault()
        handlePrevious()
      } else if (e.key === 'ArrowRight') {
        e.preventDefault()
        handleNext()
      } else if (e.key === 'Escape') {
        e.preventDefault()
        onClosePreview && onClosePreview()
      }
    }

    const handleTouchStart = (e) => {
      touchStartX = e.changedTouches[0].screenX
      touchStartY = e.changedTouches[0].screenY
    }

    const handleTouchEnd = (e) => {
      touchEndX = e.changedTouches[0].screenX
      touchEndY = e.changedTouches[0].screenY
      handleSwipe()
    }

    const handleSwipe = () => {
      const deltaX = touchEndX - touchStartX
      const deltaY = touchEndY - touchStartY
      const minSwipeDistance = 50

      // 确保水平滑动距离大于垂直滑动距离（避免与垂直滚动冲突）
      if (Math.abs(deltaX) > Math.abs(deltaY) && Math.abs(deltaX) > minSwipeDistance) {
        if (deltaX > 0) {
          // 向右滑动 - 上一个
          handlePrevious()
        } else {
          // 向左滑动 - 下一个
          handleNext()
        }
      }
    }

    document.addEventListener('keydown', handleKeyDown)
    document.addEventListener('touchstart', handleTouchStart, { passive: true })
    document.addEventListener('touchend', handleTouchEnd, { passive: true })

    return () => {
      document.removeEventListener('keydown', handleKeyDown)
      document.removeEventListener('touchstart', handleTouchStart)
      document.removeEventListener('touchend', handleTouchEnd)
    }
  }, [currentIndex, history.length])

  // 格式化日期
  const formatDate = (timestamp) => {
    const date = new Date(timestamp)
    return {
      date: date.toLocaleDateString('zh-CN', {
        month: 'short',
        day: 'numeric'
      }),
      time: date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      }),
      weekday: date.toLocaleDateString('zh-CN', {
        weekday: 'short'
      })
    }
  }

  if (!currentRecord) return null

  const dateInfo = formatDate(currentRecord.timestamp)

  return (
    <>
      {/* 左侧导航按钮 - 响应式，更透明 */}
      {currentIndex > 0 && (
        <button
          onClick={handlePrevious}
          className="fixed left-4 md:left-8 top-1/2 transform -translate-y-1/2 z-50 bg-white/8 hover:bg-white/15 active:bg-white/20 backdrop-blur-md rounded-full p-3 md:p-4 border border-white/10 hover:border-white/25 transition-all duration-300 ease-out group cursor-pointer hover:scale-110 active:scale-95"
          style={{ pointerEvents: 'auto' }}
        >
          <svg className="w-5 h-5 md:w-6 md:h-6 text-white/80 group-hover:text-white/95 transition-colors duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M15 19l-7-7 7-7" />
          </svg>
        </button>
      )}

      {/* 右侧导航按钮 - 响应式，更透明 */}
      {currentIndex < history.length - 1 && (
        <button
          onClick={handleNext}
          className="fixed right-4 md:right-8 top-1/2 transform -translate-y-1/2 z-50 bg-white/8 hover:bg-white/15 active:bg-white/20 backdrop-blur-md rounded-full p-3 md:p-4 border border-white/10 hover:border-white/25 transition-all duration-300 ease-out group cursor-pointer hover:scale-110 active:scale-95"
          style={{ pointerEvents: 'auto' }}
        >
          <svg className="w-5 h-5 md:w-6 md:h-6 text-white/80 group-hover:text-white/95 transition-colors duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
          </svg>
        </button>
      )}

      {/* 时间信息 - 右下角响应式，与预览用户输入样式一致 */}
      <div className="fixed bottom-4 md:bottom-8 right-4 md:right-8 z-30">
        <div className="poem-overlay text-white text-xs md:text-sm opacity-85 italic transform hover:scale-105 transition-all duration-500 ease-out select-none"
             style={{ userSelect: 'none', WebkitUserSelect: 'none', MozUserSelect: 'none', msUserSelect: 'none' }}>
          {dateInfo.date} · {dateInfo.weekday} · {dateInfo.time}
        </div>
      </div>

      {/* 关闭按钮 - 响应式，更透明 */}
      <button
        onClick={(e) => {
          e.preventDefault()
          e.stopPropagation()
          onClosePreview && onClosePreview()
        }}
        className="fixed top-4 md:top-8 right-4 md:right-8 z-50 bg-white/8 hover:bg-white/15 active:bg-white/20 backdrop-blur-md rounded-full p-2.5 md:p-3 border border-white/10 hover:border-white/25 transition-all duration-300 ease-out cursor-pointer hover:scale-110 active:scale-95 group"
        style={{ pointerEvents: 'auto' }}
      >
        <svg className="w-5 h-5 md:w-6 md:h-6 text-white/80 group-hover:text-white/95 group-hover:rotate-90 transition-all duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>


    </>
  )
}

export default DynamicBackground
